package com.mypack.crm.service.session.impl;

import com.mypack.crm.constants.EnumResponse;
import com.mypack.crm.constants.EnumStatus;
import com.mypack.crm.context.SessionContext;
import com.mypack.crm.dto.account.AccountDTO;
import com.mypack.crm.exception.LoginException;
import com.mypack.crm.service.account.AccountService;
import com.mypack.crm.service.session.SessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@Transactional
public class SessionServiceImpl implements SessionService {

    @Autowired
    private AccountService accountService;
    @Autowired
    @Qualifier("myRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public String login(String username, String password) throws LoginException {

        AccountDTO accountDTO = accountService.queryByUsername(username);

        if (accountDTO == null) {
            throw new LoginException(EnumResponse.NOT_EXIST_USER);
        }

        if (EnumStatus.INACTIVE.getCode().equals(accountDTO.getStatus())) {
            throw new LoginException(EnumResponse.LOGIN_INVALID_STATUS);
        }

        if (DigestUtils.md5DigestAsHex(password.getBytes()).equals(accountDTO.getPassword())) {
            log.info("{}账号校验成功！", accountDTO.getUsername());
            String token = System.currentTimeMillis() + "";
            redisTemplate.opsForValue().set(token, accountDTO, 2, TimeUnit.HOURS);
            return token;
        } else {
            throw new LoginException(EnumResponse.FAIL);
        }

    }
}
